﻿using Common;
using Common.AJControls;
using Common.EF.Controllers;
using Common.Model;
using Common.Models;
using Common.Utility;
using MaterialDesignThemes.Wpf;
using NPOI.SS.UserModel;
using Stylet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;

namespace AWSV2.ViewModels
{
    public class WeighingRecordRelationViewModel : Screen
    {
        private IWindowManager _windowManager;
        private IEventAggregator _eventAggregator;

        #region 分页配置

        private AJTablePagination _pagination;
        public AJTablePagination Pagination
        {
            get
            {
                return _pagination;
            }
            set
            {
                SetAndNotify(ref _pagination, value);
            }
        }

        public void PrevOrNextPageChangeCmd(string parameter)
        {
            var changed = false;
            var prev = parameter.Contains('上');
            if (prev)
            {
                if (Pagination.CanPrevPage)
                {
                    Pagination.Current -= 1;
                    changed = true;
                }
            }
            else
            {
                if (Pagination.CanNextPage)
                {
                    Pagination.Current += 1;
                    changed = true;
                }
            }

            if (changed)
            {
                ExecuteGetListCmd(null);
            }
        }

        public void PageItemCheckedCmd(object sender, RoutedEventArgs e)
        {
            e.Handled = true;
            if (e.OriginalSource is ToggleButton tgb)
            {
                var parameter = tgb.DataContext as AJTablePageItem;
                if (parameter.PageNumber.Equals("···"))
                {
                    var prev = parameter.IsPageJumper == true;
                    var current = prev
                        ? new int[] { 1, Pagination.Current - 5 }.Max()
                        : new int[] { Pagination.Total, Pagination.Current + 5 }.Min();

                    Pagination.Current = current;
                    return;
                }
                Pagination.Current = Convert.ToInt32(parameter.PageNumber);
                ExecuteGetListCmd(null);
            }

        }

        #endregion

        private bool _loading;
        public bool Loading
        {
            get
            {
                return _loading;
            }
            set
            {
                SetAndNotify(ref _loading, value);
            }

        }

        private BindableCollection<WeighingRecordRelation> _rows;
        public BindableCollection<WeighingRecordRelation> Rows
        {
            get
            {
                return _rows;
            }
            set
            {
                SetAndNotify(ref _rows, value);
            }

        }

        private WeighingRecordRelation _current;
        public WeighingRecordRelation Current
        {
            get => _current;
            set => SetAndNotify(ref _current, value);
        }

        public string _search;
        public string Search
        {
            get
            {

                return _search;
            }
            set
            {
                _search = value;
            }
        }

        public WeighingRecordRelationViewModel(IWindowManager windowManager, IEventAggregator eventAggregator)
        {
            CurrentLoginId = Globalspace._currentUser.LoginId;
            _windowManager = windowManager;

            Pagination = new AJTablePagination();

            Rows = new BindableCollection<WeighingRecordRelation>();

            //_importOptions = new AJTableImportOptions
            //{
            //    ImportType = typeof(CarExcelModel),
            //    TemplateRowsHandler = () =>
            //    {
            //        return new List<object> {
            //            new CarExcelModel
            //            {
            //                PlateNo = "贵C12345",
            //                VehicleWeight = 0,
            //                CarOwner =  "选填",
            //                LabelNo = "选填",
            //                BeginDate = "选填,日期格式 2024-6-28 10:48:00",
            //                EndDate = "选填,日期格式 2024-6-28 10:48:00",
            //                Driver = "选填",
            //                DriverPhone = "选填",
            //                Comment = string.Empty,
            //            }
            //        };
            //    },
            //    ImportDataItemProcessHandler = (rows) =>
            //    {
            //        using var ctrl = new CarController();
            //        var mapper = AJAutoMapperService.Instance().Mapper;
            //        var importForm = new Common.EF.Tables.CarBatchImportForm();
            //        var rowList = rows.Select(p => (Car)((CarExcelModel)p)).ToList();
            //        var importTask = Task.Run(() =>
            //        {
            //            importForm.Rows = mapper.Map<List<Car>, List<Common.EF.Tables.Car>>(rowList);
            //            return ctrl.Import(importForm);
            //        });
            //        importTask.Wait();
            //        return importTask.Result;
            //    },
            //    ImportCompleteHandler = () =>
            //    {
            //        var result = new ProcessResult();
            //        result.SetSuccess();
            //        return Task.FromResult(result);
            //    }
            //};
            _eventAggregator = eventAggregator;
        }

        public void OpenForm(bool addMode)
        {
            var viewModel = new WeighingRecordRelationDetailViewModel(addMode ? null : _current);
            bool? result = _windowManager.ShowDialog(viewModel);

            if (result.GetValueOrDefault(true))
            {
                ExecuteGetListCmd(null);
            }
        }

        public void OnSearchKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                ExecuteGetListCmd(null);
            }
        }

        #region 行选择功能 --阿吉 2024年4月25日10点43分

        private CheckBox _allRowCheckbox;
        private bool _allRowCheckboxProcess;

        private string _currentLoginId;
        public string CurrentLoginId { get => _currentLoginId; set => SetAndNotify(ref _currentLoginId, value); }

        private bool _canDeleteSelected;
        public bool CanDeleteSelected
        {
            get
            {
                _canDeleteSelected = Rows.Any(p => p.Checked);
                return _canDeleteSelected;
            }
            set { SetAndNotify(ref _canDeleteSelected, value); }
        }


        public async void DeleteSelected()
        {
            var selected = Rows.Where(p => p.Checked).ToList();

            var result = MessageBox.Show(I18NService.Translate(LangKeys.确认删除_0_条数据吗, selected.Count),
                 I18NService.Translate(LangKeys.提示), MessageBoxButton.OKCancel);

            if (result == MessageBoxResult.OK)
            {
                using var ctrl = new WeighingRecordRelationController();
                var deleteRet = await ctrl.MultiDelete(selected.Select(p => p.Id));

                if (deleteRet == 0)
                {
                    MessageBox.Show(I18NService.Translate(LangKeys.未删除任何数据), I18NService.Translate(LangKeys.删除失败), MessageBoxButton.OK);
                    return;
                }

                ExecuteGetListCmd(null);

            }
        }

        public void RowCheckedChangedHandle(object sender, System.Windows.RoutedEventArgs e)
        {
            if (_allRowCheckboxProcess)
            {
                return;
            }
            var cbx = ((CheckBox)sender);
            var view = cbx.DataContext as WeighingRecordRelation;

            if (view == null)
            {
                return;
            }
            view.Checked = cbx.IsChecked.GetValueOrDefault();

            var checkedCount = 0;

            foreach (var row in Rows)
            {
                if (row.Checked)
                {
                    checkedCount++;
                }
            }

            _allRowCheckbox.IsThreeState = checkedCount > 0 && checkedCount != Rows.Count;
            if (_allRowCheckbox.IsThreeState)
            {
                _allRowCheckbox.IsChecked = null;
            }
            else
            {
                _allRowCheckbox.IsChecked = checkedCount == Rows.Count;
            }
            CanDeleteSelected = Rows.Any(p => p.Checked);
        }


        public void AllRowCheckBox_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            _allRowCheckbox = (CheckBox)sender;
        }

        public void AllRowCheckedChangedHandle(object sender, System.Windows.RoutedEventArgs e)
        {
            _allRowCheckboxProcess = true;
            var cbx = ((CheckBox)sender);
            cbx.IsThreeState = !cbx.IsChecked.HasValue;
            if (cbx.IsChecked != null && cbx.IsChecked.HasValue)
            {
                foreach (var row in Rows)
                {
                    row.Checked = cbx.IsChecked.GetValueOrDefault();
                }
            }
            _allRowCheckboxProcess = false;
            CanDeleteSelected = Rows.Any(p => p.Checked);
        }

        public async void ExecuteGetListCmd(bool? isExport)
        {
            Loading = true;
            using var ctrl = new WeighingRecordRelationController();

            var paged = await ctrl.Pages(Search, Pagination.Current, Pagination.PageSize);

            Loading = false;

            Pagination.Total = paged.TotalCount;

            Rows = new BindableCollection<WeighingRecordRelation>(AJAutoMapperService.Instance()
                .Mapper.Map<List<Common.EF.Tables.WeighingRecordRelation>, List<WeighingRecordRelation>>(paged.Data));
        }

        #endregion
    }
}
